import {createRouter, createWebHashHistory} from 'vue-router'
import type {RouteLocationNormalized, NavigationGuardNext, RouteRecordRaw, Router} from 'vue-router'
import {useCounterStore} from "@/store/counter";
import {generateRouters} from "@/layout/MenuUtils/generateRouter";
import {getToken} from "@/utils/auth";
import Layout from '@/layout/layout.vue'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';


const staticRoutes: RouteRecordRaw[] = [
    {
        path: '/',
        name: 'Layout',
        redirect: '/home',
        component: Layout,
    },
    {
        path: "/:pathMatch(.*)*",
        name: "404",
        component: () => import('@/views/error/404/index.vue')
    },
    {
        path: '/:catchAll(.*)',
        component: () => import('@/views/error/404/index.vue')
    },
    {
        path: "/login",
        name: "Login",
        component: () => import('@/views/login/login.vue'),
    },
]
/**
 * @description 📚 路由参数配置简介
 * @param path ==> 路由菜单访问路径
 * @param name ==> 路由 name (对应页面组件 name)
 * @param component ==> 前端组件文件路径
 * @param meta ==> 路由菜单元信息
 * @param meta.icon ==> 菜单和面包屑对应的图标
 * @param meta.title ==> 路由标题 (用作 document.title || 菜单的名称)
 * @param meta.hidden ==> 是否在菜单中隐藏 (通常列表详情页需要隐藏)
 * @param meta.activeMenu ==> 激活左侧菜单位置（需写在二级路由后的嵌套路由每一个meta里，主要是为了页面处于嵌套路由中默认选中并高亮一级菜单）
 * @param meta.keepAlive ==> 当前路由是否缓存
 * @param redirect ==> 当点击面包屑目录时路由重定向地址（该属性需写在一级目录路由上）
 * @param breadHidden ==> 是否隐藏顶部面包屑（该属性需写在非目录路由的视图路由meta中）
 * @param tagHidden ==> 是否隐藏顶部标签导航（该属性需写在非目录路由的视图路由meta中）
 * */
const router: Router = createRouter({
    history: createWebHashHistory(),
    routes: staticRoutes,
    strict: false,
    scrollBehavior: () => ({left: 0, top: 0})
})

enum ELOGINSTATE {
    ISLOGIN = '/Login'
}

router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): Promise<void> => {
    NProgress.start()
    const token = getToken();
    const store = useCounterStore() as any
    if (!token && to.path == ELOGINSTATE.ISLOGIN) {
        store.$patch({roles: []})
        store.$patch({menuTree: []})
        store.$patch({menuList: []})
        // 未登录 去的是登录页面
        next();
    } else if (!token && to.path !== ELOGINSTATE.ISLOGIN) {
        // 未登录 去的不是登录页面
        store.$patch({roles: []})
        store.$patch({menuTree: []})
        next(`/Login?redirect=${to.fullPath}`)
        NProgress.done()
    } else if (token && to.path == ELOGINSTATE.ISLOGIN) {
        // 已登录 去的是登录页面
        next({path: "/"});
    } else if (token && to.path !== ELOGINSTATE.ISLOGIN) {
        // 已登录但是没有用户菜单
        if (store.roles.length > 0) {
            if (to.matched.length == 0) {
                from.path ? next({path: from.path}) : next({name: '404'});
            } else {
                next();
            }
        } else {
            if (store.menuTree.length == 0) {
                try {
                    await store.getUserInfo()
                    await store.getMenuTree()
                    const newMenuTree: any[] = generateRouters(store.menuList)
                    newMenuTree.map(item => {
                        router.addRoute('Layout', item);
                    })
                    next({...to, replace: true});

                } catch (e) {
                    await store.logOut()
                    next(`/Login?redirect=${to.fullPath}`);
                    NProgress.done();
                }
            }
        }
    }
})
router.afterEach(() => {
    NProgress.done()
})

NProgress.configure({
    easing: 'ease',
    speed: 1000,
    showSpinner: false,
    trickleSpeed: 200,
    minimum: 0.3
})
export default router
